#include "ipgiver.h"

IpGiver::IpGiver(int ipgPort)
{
	this->ipgPort = ipgPort;
}

STATUS 
IpGiver::InitNetwork()
{
	FILL_SOCKADDR_IN_INT(ipgAddr, AF_INET, ipgPort, INADDR_ANY);
	len = sizeof(struct sockaddr);

	ipgSock = socket(AF_INET, SOCK_DGRAM, 0); 
	if (ipgSock == SOCKET_ERROR) 
	{
		DEBUGS("ipgiver: socket error (%s)", strerror(errno));
		return SOCKET_ERROR;
	}

	ret = bind(ipgSock, (struct sockaddr*) &ipgAddr, sizeof(ipgAddr)); 
	if (ret == BIND_ERROR) 
	{
		DEBUGS("ipgiver: bind error (%s)", strerror(errno));
		return BIND_ERROR;
	}
}

STATUS 
IpGiver::Listen()
{
	while (true)
	{
		/** Wait 2 seconds. */
		tv.tv_sec = 2;
		tv.tv_usec = 0;

		FD_ZERO(&readFds);
		FD_SET(ipgSock, &readFds);

		ret = select(ipgSock+1, &readFds, NULL, NULL, &tv);
		if (ret == SELECT_ERROR)
		{
			DEBUGS("ipgiver: select error (%s)", strerror(errno));
			return SELECT_ERROR;
		}

		DEBUGS("ipgiver: waiting for slaves to connect");

		char msg = 0;

		if (FD_ISSET(ipgSock, &readFds))
		{
			DEBUGS("ipgiver: slave connected");

			recvfrom(ipgSock, &msg, sizeof(char), 0, (struct sockaddr*) &cliAddr, &len);
			if (msg == ARE_YOU_NUMFAC)
			{
				msg = I_AM_NUMFAC;
				sendto(ipgSock, &msg, sizeof(char), 0, (struct sockaddr*) &cliAddr, sizeof(cliAddr));
				sendto(ipgSock, &MY_IP, sizeof(unsigned int), 0, (struct sockaddr*) &cliAddr, sizeof(cliAddr));
			}
		}
	}
}
